package com.hgyc.mom.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hgyc.mom.system.entity.SysRoleMenu;
import com.hgyc.mom.system.service.SysRoleMenuService;
import com.hgyc.mom.system.vo.RoleMenuVO;
import com.hgyc.mom.system.mapper.SysRoleMenuMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统角色菜单信息 服务实现类
 * </p>
 *
 * @author fwj
 * @since 2025-01-16
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRoleResource(RoleMenuVO roleMenuVO) {
        //先删除角色所有的权限
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleMenuVO.getRoleId());
        this.remove(wrapper);

        //新增角色权限关联数据
        if (!CollectionUtils.isEmpty(roleMenuVO.getSourceIds())) {
            List<SysRoleMenu> roleMenuList = new ArrayList<>();
            for (Long sourceId : roleMenuVO.getSourceIds()) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(roleMenuVO.getRoleId());
                sysRoleMenu.setMenuId(sourceId);
                roleMenuList.add(sysRoleMenu);
            }
            saveBatch(roleMenuList);
        }
    }

    @Override
    public void deleteByMenuId(Long menuId) {
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getMenuId, menuId);
        this.remove(wrapper);
    }
}
